package com.example.forum.exception;

import com.example.forum.common.AppResult;
import com.example.forum.common.enums.ResultCode;
import io.swagger.v3.oas.annotations.Hidden;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author hanzishuai
 * @date 2025/3/22 9:33
 * @Description 处理全局异常
 */
@Slf4j
@ControllerAdvice
@Hidden
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(ApplicationException.class)
    public AppResult applicationExceptionHandler(ApplicationException e) {
        e.printStackTrace();

        log.error(e.getMessage());
        if (e.getErrorResult() != null) {
            return e.getErrorResult();
        }

        if (!StringUtils.hasLength(e.getMessage())) {
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }

        // 返回具体的异常信息
        return AppResult.failed(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public AppResult exceptionHandler(Exception e) {
        e.printStackTrace();

        log.error(e.getMessage());

        if (!StringUtils.hasLength(e.getMessage())) {
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }

        return AppResult.failed(e.getMessage());
    }
}
